package com.emps_vue.demo.Controller;

import com.emps_vue.demo.Entity.User;
import com.emps_vue.demo.Service.RegesterService;
import com.emps_vue.demo.utils.VerifyCodeUtils;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin //允许跨域
@RequestMapping("user")
public class GetImage {
    @Resource
    private RegesterService regesterService;

    @RequestMapping("register")
    public Map<String, Object> register(@RequestBody User user, String code, HttpServletRequest res) {
        Map<String, Object> map = new HashMap<>();
        try {
            if (code.equalsIgnoreCase((String) res.getServletContext().getAttribute("code"))) {
                regesterService.register(user);
                map.put("state", true);
                map.put("msg", "注册成功！");
            } else {
                throw new RuntimeException("验证码错误！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "注册失败！");
        }
        return map;
    }

    @RequestMapping("getImage")
    public String getImageCode(HttpServletRequest request) throws IOException {
        //1.使用工具类生成验证码
        String code = VerifyCodeUtils.generateVerifyCode(4);
        //2.将验证码放入servletContext作用域
        request.getServletContext().setAttribute("code", code);
        //3.将图片转为base64
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(120, 30, byteArrayOutputStream, code);
        return "data:image/png;base64," + Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());
    }

    @RequestMapping("login")
    public Map<String, Object> Login(@RequestBody User user) {
        Map<String, Object> map = new HashMap<>();
        try {
            User user2 = regesterService.login(user);
            map.put("state", true);
            map.put("msg", "登陆成功");
            System.out.println(user2);
            map.put("user", user2);
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }
}
